package com.zhouwj.utils.ViewUtils;

import android.content.Context;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;

import com.zhouwj.utils.ViewUtils.Model.BaseModel;

import java.util.List;

/**
 * Created by Administrator on 2016/12/7.
 */

public class PopupMenuUtils {
    private final String TAG = PopupMenuUtils.class.getSimpleName();
    private volatile static PopupMenuUtils mInstance;
    private onMenuTextItemClickListener mListener;
    private PopupMenu mPopupMenu;
    private View mCurrentView;

    public static PopupMenuUtils getInstance(){
        if (mInstance == null) {
            synchronized (PopupMenuUtils.class) {
                if (mInstance == null) {
                    mInstance = new PopupMenuUtils();
                }
            }
        }
        return mInstance;
    }

    public interface onMenuTextItemClickListener{
        void onMenuTextItemClickListener(View view, int position, BaseModel model);
    }

    public void setOnMenuTextItemClickListener(onMenuTextItemClickListener listener){
        mListener = listener;
    }

    public void showPopupMenu(Context context, final View view, final List<? extends BaseModel> list){
        if (mCurrentView != view) {
            mPopupMenu = null;
        }
        if(mPopupMenu==null){
            mPopupMenu = new PopupMenu(context,view);
            addTypeMenu(list);
            mPopupMenu.setOnMenuItemClickListener(new android.widget.PopupMenu.OnMenuItemClickListener() {

                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    if(mListener==null){
                        Log.e(TAG,"Please setOnMenuTextItemClickListener");
                        return true;
                    }
                    mListener.onMenuTextItemClickListener(view, item.getOrder(),list.get(item.getOrder()));
                    return true;
                }
            });
            mCurrentView = view;
        }
        mPopupMenu.show();
    }

    private void addTypeMenu(List<? extends BaseModel> list) {
        for (int i = 0; i < list.size(); i++) {
            mPopupMenu.getMenu().add(0, 0, i, list.get(i).getName());
        }
    }
}
